<template>
	<div class="default-main">

		<cus-form id="landform-form" collapsable icon="fa fa-search" label="搜索">
			<template #title-after>
				<el-button :disabled="!!editingId" icon="el-icon-Search" size="small" type="primary" @click.stop="handleSearch">
					搜索
				</el-button>
				<el-button :disabled="!!editingId" icon="el-icon-Refresh" size="small" type="primary" @click.stop="resetSearch">
					重置
				</el-button>
			</template>
			<template #form>
				<el-form ref="searchForm" :model="params" label-width="auto" @submit.prevent>
					<el-row :gutter="20" justify="start">
						<el-col :span="8">
							<el-form-item label="地貌名称">
								<el-input v-model="params.landformName_like" clearable placeholder="模糊查询" @keyup.enter="handleSearch"/>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</template>
		</cus-form>

		<cus-table-title id="landform-table-title" icon="local-cus-landform" label="地貌">
			<template #after>
				<el-button :disabled="!!editingId" icon="el-icon-Plus" size="small" style="margin-left: 20px" type="primary" @click="toAdd">
					新增
				</el-button>
			</template>
		</cus-table-title>
		<el-table v-loading="tableLoading" :data="landformTableData" :max-height="tableMaxHeight" border class="cus-table" fit highlight-current-row>
			<el-table-column align="center" label="序号" width="60">
				<template v-slot="scope">
					{{ initTableIndex(pageRef, scope.$index) }}
				</template>
			</el-table-column>
			<el-table-column label="地貌名称" min-width="150">
				<template v-slot="{row}">
					<template v-if="row.edit">
						<el-input v-model="row.landformName" class="edit-input" size="small"/>
						<el-button
								class="cancel-btn"
								icon="el-icon-Refresh"
								size="small"
								type="warning"
								@click="cancelEdit(row)"
						>
							取消
						</el-button>
					</template>
					<span v-else>
            <el-tag>{{ row.landformName }}</el-tag>
          </span>
				</template>
			</el-table-column>
			<el-table-column align="center" fixed="right" label="操作" width="130">
				<template v-slot="{row}">
					<el-button v-show="row.edit" v-auth="'g-landform:saveLandform'" icon="el-icon-CircleCheck" size="small"
					           type="success" @click="confirmEdit(row)"
					></el-button>
					<el-button v-show="!row.edit" :disabled="!!editingId && row.id!==editingId" icon="el-icon-Edit" size="small"
					           type="primary" @click="toEdit(row)"
					></el-button>
					<el-popconfirm :hide-after="0" :title="'删除该地貌（'+row.landformName+'）？'" confirm-button-type="danger"
					               width="auto" @confirm="deleteLandform(row)">
						<template #reference>
							<el-button v-auth="'sys-user:deleteUser'" :disabled="!!editingId" icon="el-icon-Delete" size="small"
							           type="danger"></el-button>
						</template>
					</el-popconfirm>
				</template>
			</el-table-column>
		</el-table>
		<cus-pagination id="landform-pagination" ref="pageRef" v-model="landformTableData" v-model:loading="tableLoading" :pageSize="10" :params="params"
		                url="/game/g-landform/readOnly/searchLandformByPage" @refreshDone="refreshDone"/>

		<!-- 对话框（新增） -->
		<el-dialog v-model="dialogVisible" :close-on-click-modal="false" :close-on-press-escape="true" append-to-body center
		           class="cus-dialog" destroy-on-close draggable title="新增" width="50%">
			<el-form ref="addFormRef" :model="landform" :rules="rules" label-width="auto">
				<el-form-item label="地貌名称" prop="landformName">
					<el-input v-model="landform.landformName" clearable maxlength="100"/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button v-auth="'g-landform:saveLandform'" icon="el-icon-CircleCheck" type="primary" @click="save">
					保存
				</el-button>
				<el-button icon="el-icon-CircleClose" type="warning" @click="dialogVisible = false">
					取消
				</el-button>
			</template>
		</el-dialog>

	</div>
</template>

<script lang="ts" name="Landform" setup>

import {deleteLandformApi, saveLandformApi} from '@/api/gameData/landform.api'
import {onActivated, onMounted, reactive, ref, watch} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {focusFormErrorElement, initTableIndex, messageSuccess} from '@/utils/commonUtil'
import {useI18n} from 'vue-i18n'
import CusPagination from '@/components/cus-pagination.vue'
import CusTableTitle from '@/components/cus-table-title.vue'
import type {DebouncedFunc} from 'lodash-es'
import {debounce} from 'lodash-es'
import {calcMaxHeight} from '@/utils/layoutUtil'
import {useEventListener} from '@vueuse/core'
import {onBeforeRouteLeave} from 'vue-router'
import CusForm from '@/components/cus-form.vue'

const {t} = useI18n()

const pageRef = ref()
const addFormRef = ref<FormInstance>()

const tableLoading = ref(false)
const tableMaxHeight = ref<number>(800)
const params = reactive({
	landformName_like: undefined
})
const dialogVisible = ref(false)
const landformTableData = ref<LandformRow[]>([])
const editingId = ref<number>()
const landform = reactive({
	id: undefined,
	landformName: undefined,
	createTime: undefined,
	updateTime: undefined
})
const rules = reactive<FormRules>({
	landformName: [
		{required: true, message: '请输入地貌名称', trigger: 'change'}
	]
})

watch(landformTableData, () => {
	for (const landform of landformTableData.value) {
		Reflect.set(landform, 'edit', false)
		Reflect.set(landform, 'originalLandformName', landform.landformName)
	}
})

// 计算表格最大高度
const getTableMaxHeight: DebouncedFunc<() => typeof getTableMaxHeight> = debounce(() => {
	tableMaxHeight.value = calcMaxHeight('#landform-form', '#landform-table-title', '#landform-pagination')
	return getTableMaxHeight
}, 100, {
	leading: true,
	trailing: false,
	maxWait: 100
})

const handleSearch = () => {
	pageRef.value.reload()
}

const resetParams = () => {
	params.landformName_like = undefined
}

const resetSearch = () => {
	resetParams()
	handleSearch()
}

const toEdit = (row: LandformRow) => {
	editingId.value = row.id
	row.edit = true
}

const cancelEdit = (row: LandformRow) => {
	row.landformName = row.originalLandformName
	row.edit = false
	editingId.value = undefined
}

const confirmEdit = (row: LandformRow) => {
	saveLandformApi(row).then(() => {
		editingId.value = undefined
		messageSuccess('更新成功')
		pageRef.value.buildData()
	})
}

const deleteLandform = (row: LandformRow) => {
	deleteLandformApi(row.id!).then(() => {
		messageSuccess('删除成功')
		pageRef.value.buildData()
	})
}

const resetLandform = () => {
	landform.id = undefined
	landform.landformName = undefined
	landform.createTime = undefined
	landform.updateTime = undefined
}

const toAdd = () => {
	resetLandform()
	dialogVisible.value = true
}

const save = () => {
	addFormRef.value!.validate(pass => {
		if (pass) {
			saveLandformApi(landform).then(() => {
				messageSuccess(t('successMessage.add'))
				dialogVisible.value = false
				pageRef.value.buildData()
			})
		} else {
			focusFormErrorElement()
		}
	})
}

const refreshDone = () => {
	editingId.value = undefined
}

onMounted(() => {
	useEventListener(window, 'resize', getTableMaxHeight()!)
})

// 该页面开启缓存且首次或后续进入时执行，刷新页面不执行
onActivated(() => {
	useEventListener(window, 'resize', getTableMaxHeight()!)
})

onBeforeRouteLeave(() => {
	window.removeEventListener('resize', getTableMaxHeight)
})

</script>

<style scoped>
.edit-input {
	padding-right: 100px;
}

.cancel-btn {
	position: absolute;
	right: 15px;
	top: 10px;
}
</style>
